<template>
  <div class="container">
    <div class="app-container">
      <!-- 树形组件 el-tree -->
      <el-tree :expand-on-click-node="false" default-expand-all :data="depts" :props="defaultProps">
        <template #default="{ data }">
          <!-- align 垂直方向居中 -->
          <el-row style="width: 100%; height: 40px" align="middle" type="flex" justify="space-between">
            <span>{{ data.name }}</span>
            <el-col :span="4">
              <!-- 负责人 -->
              <span class="manager-name">{{ data.managerName }}</span>
              <!-- 下拉菜单 -->
              <el-dropdown @command="handleCommand(data.id, $event)">
                <span class="el-dropdown-link">
                  操作<i class="el-icon-arrow-down el-icon--right" />
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="add">添加子部门</el-dropdown-item>
                  <el-dropdown-item command="edit">编辑部门</el-dropdown-item>
                  <el-dropdown-item command="del">删除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-col>
          </el-row>

        </template>

      </el-tree>
    </div>
    <addDept ref="addDept" :current-node-id="currentNodeId" :show-dialog.sync="showDialog" @updateDepartment="getDepartmentList" />
  </div>
</template>
<script>
import { getDepartmentList } from '@/api/department'
import { translateListToTreeeData } from '@/utils'
import addDept from './components/add-dept.vue'
export default {
  name: 'Department',
  components: {
    addDept
  },
  data() {
    return {
      depts: [
      ],
      defaultProps: {
        children: 'children',
        label: 'name' // 标签文本字段
      },
      showDialog: false, // 弹层显示
      currentNodeId: null // 当前部门/节点id
    }
  },
  created() {
    this.getDepartmentList()
  },
  methods: {
    // 获取部门列表
    async getDepartmentList() {
      const res = await getDepartmentList()
      // console.log(res)
      this.depts = translateListToTreeeData(res, 0)
    },
    // 下拉菜单 - 操作
    handleCommand(id, type) {
      console.log(id, type)
      // 添加子部门
      if (type === 'add') {
        this.currentNodeId = id
        this.showDialog = true
      } else if (type === 'edit') {
        // 编辑部门
        this.currentNodeId = id
        this.showDialog = true
        // 调用子组件身上的获取部门详情的方法 (表单渲染)
        // currentNodeId null
        // 原因: 显示子组件, 内部的数据/方法, 并没有构建完成
        //      父组件更新子组件的props ==> 异步的
        // 解决方案:
        // 让子组件完全构建成功, 再调用子组件身上的方法
        // 晚一点调用子组件的方法 ..... 等它完全渲染完成....
        this.$nextTick(() => {
          // vue更新dom的过程是异步的
          // 批量的更新 - 提高更新性能
          this.$refs.addDept.getDepartmentDetail()
        })
      }
    }
  }
}
</script>
<style scoped lang="scss">
  .app-container {
    padding: 32px 140px;
    font-size: 14px;
  }
  .manager-name {
    width: 80px;
    display: inline-block;
    // margin-right: 10px;
  }
</style>
